<template>
  <view class="station">
    <view class="business_model">
      <view class="business_name">油福同享</view>
      <view class="tip">甄选油品/省钱加油/优质服务</view>
    </view>
    <swiper class="swiper-box">
      <swiper-item v-for="(item, index) in iamges" :key="index">
        <view class="swiper-item">
          <image :src="item.url" mode="scaleToFill" />
        </view>
      </swiper-item>
    </swiper>
    <view class="station_list">
      <view class="preference">慧优选</view>
      <view v-if="phoneNumber" class="station_item" v-for="(item, index) in fuelList" :key="index" @click="goOfficial(item)">
        <view class="item_top_model">
          <view class="item_left">
            <image src="../../static/fuel/oil_gun.png" mode="scaleToFill" />
            <view>{{ item.stationName }}</view>
          </view>
          <view class="item_right">
            <image src="../../static/fuel/distance.png" mode="scaleToFill" />
            <view>{{ getDistances(item.stationLatitude, item.stationLongitude) }}</view>
          </view>
        </view>
        <view class="oil_price">
          <!-- <view> <text>￥</text><text>7.10</text> </view> -->
          <!-- <text class="station_price">油站价￥7.5</text> -->
        </view>
        <view class="oil_address">{{ item.detailRegionData }}</view>
        <view class="refuel">
          <text>立即加油</text>
        </view>
      </view>
      <view v-else>
        <view class="station_item" v-for="(item, index) in fuelList" :key="index">
          <button id="phone" plain open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="phone_main">
            <view class="item_top_model">
              <view class="item_left">
                <image src="../../static/fuel/oil_gun.png" mode="scaleToFill" />
                <view>{{ item.stationName }}</view>
              </view>
              <view class="item_right">
                <image src="../../static/fuel/distance.png" mode="scaleToFill" />
                <view>{{ getDistances(item.stationLatitude, item.stationLongitude) }}</view>
              </view>
            </view>
            <view class="oil_price">
              <!-- <view> <text>￥</text><text>7.10</text> </view> -->
              <!-- <text class="station_price">油站价￥7.5</text> -->
            </view>
            <view class="oil_address">{{ item.detailRegionData }}</view>
            <view class="refuel">
              <text>立即加油</text>
            </view>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapMutations } from "vuex";
import settings from "@/settings.js";
export default {
  data() {
    return {
      iamges: [
        {
          url: require("../../static/fuel/swiper.png"),
        },
      ],
      fuelList: [],
      latitude: 0, // 纬度
      longitude: 0, // 经度
      descentPrice: "0.40", // 直降价格
      appletShowOilNamePrice: "", // 展示油号
      userInfo: {},
      stationId: settings.stationId,
    };
  },
  created() {
    this.init();
  },
  computed: {
    // 展示的油站信息
    selectStaOilGunList() {
      return (
        this.fuelList.map((item) => {
          if (item.oilList) {
            const obj = item.oilList.find((val) => val.oilName === this.appletShowOilNamePrice) || {};
            return obj;
          }
          return item;
        }) || []
      );
    },
  },
  onLoad() {
    this.updateEnterpriseId(settings.enterpriseId);
  },
  onShow() {
    const this_ = this;
    if (this.phoneNumber) {
      this.getUserInfo();
    } else {
      this.getOpenId();
    }
    if (!this.userInfo) {
      wx.getUserInfo({
        success: function (res) {
          this_.gender = res.userInfo.gender;
        },
      });
    }
  },
  watch: {
    phoneNumber(newval, oldval) {
      if (this.phoneNumber) {
        this.getUserInfo();
      }
    },
    enterpriseId(newval, oldval) {
      // 康裕石化能源： 生产id是 137  测试id是194
      if (this.enterpriseId !== settings.stationId) {
        this.getOpenId();
      }
    },
  },
  methods: {
    ...mapMutations({
      updateOpenId: "updateOpenId",
      updatePhoneNumber: "updatePhoneNumber",
      updateEnterpriseId: "updateEnterpriseId",
    }),
    async init() {
      const that = this;
      // uni.getLocation({
      //   type: "wgs84",
      //   success: function (res) {
      //     console.log(res, "获取定位成功");
      //     that.latitude = res.latitude; //纬度，浮点数，范围为90 ~ -90
      //     that.longitude = res.longitude; //经度，浮点数，范围为180 ~ -180。
      //   },
      //   fail: function (res) {
      //     console.log(res, "eee");
      //     uni.showModal({
      //       title: "您未开启手机地理位置",
      //       content: "小程序将无法正常使用",
      //       success: (res) => {
      //         if (res.confirm) {
      //           uni.openSetting();
      //         }
      //       },
      //     });
      //   },
      // });
      try {
        const res = await this.$Request({
          url: "/appletSelectStationList",
          method: "GET",
          data: { enterpriseId: this.enterpriseId },
        });
        if (res.retCode !== 0) {
          throw new Error("获取油站失败");
        }
        this.fuelList = res.data.stationList || [];
        // if (res.data.stationList && res.data.stationList.length === 1) {
        //   this.goOfficial();
        // }
        this.appletShowOilNamePrice = res.data.appletShowOilNamePrice || "92#";
      } catch (error) {
        uni.showToast({
          title: error,
          icon: "error",
        });
      }
    },
    async getUserInfo() {
      try {
        if (this.phoneNumber) {
          const infoData = await this.$Request({
            url: "/selectMemberInfo",
            method: "GET",
            data: {
              enterpriseId: this.enterpriseId,
              mobilePhone: this.phoneNumber,
            },
          });
          if (infoData.retCode !== 0) {
            throw new Error(infoData.message);
          }
          this.userInfo = infoData.data;
        }
      } catch (error) {}
    },
    // 获取手机号
    async getPhoneNumber(info) {
      uni.showLoading({
        title: "获取中...",
        mask: true,
      });
      if (info.detail.errMsg === "getPhoneNumber:ok") {
        // let pc = new WXBizDataCrypt('wx3d56fc8b214444d2', this.session_key);
        // let pc = new WXBizDataCrypt('wxf24a5561a44f6d55', this.session_key); //
        // let data = pc.decryptData(info.detail.encryptedData , info.detail.iv);
        const encryptedData = info.detail.encryptedData;
        const iv = info.detail.iv;
        const infoData = await this.$Request({
          url: "/loginGetPhone",
          method: "GET",
          data: {
            code: this.code,
            stationId: this.stationId,
            encryptedData,
            iv,
            version: 2,
            blogNickName: "微信用户",
            sexFlag: this.gender || 0,
            blogProfilePhoto: this.avatarUrl,
          },
        });
        const openId = infoData.data.openId;
        this.updateOpenId(openId);
        const phone = infoData.data.phoneNumber;
        this.phoneNumber = infoData.data.phoneNumber;
        this.updatePhoneNumber(phone);
        uni.hideLoading();
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "请授权登录~",
          icon: "error",
        });
        this.getOpenId();
      }
    },
    async getOpenId() {
      const this_ = this;
      uni.login({
        provider: "weixin",
        success: async (res) => {
          this_.code = res.code;
        },
      });
    },
    getDescentPrice(val) {
      return Number((Number(val) - Number(this.descentPrice)).toFixed(2));
    },

    goOfficial(val) {
      // 调用 uni.getSetting() 函数获取用户的设置信息
      uni.getSetting({
        success(res) {
          // res.authSetting['scope.userLocation'] 表示用户对于获取位置信息的授权状态
          if (res.authSetting["scope.userLocation"]) {
            console.log("已授权获取位置");
          } else {
            console.log("未授权获取位置");
          }
        },
      });
      let item = val;
      if (!val) {
        item = this.fuelList[0];
        if (!item) {
          uni.showToast({
            title: "当前没有可用油站",
            icon: "error",
          });
          return;
        }
      }
      uni.setStorageSync(
        "stationData",
        JSON.stringify({
          appletShowOilNamePrice: this.appletShowOilNamePrice,
          ...item,
        })
      );
      const distances = this.getDistances(item.stationLatitude, item.stationLongitude);
      uni.navigateTo({
        url: `/subPack/fuel/remit?stationId=${item.stationId}&stationName=${item.stationName}&distances=${distances}`,
      });
    },

    openLocation(item) {
      let longitude = Number(item.stationLongitude).toFixed(0);
      let latitude = Number(item.stationLatitude).toFixed(0);
      if (Number(latitude) > 90 || Number(latitude) < -90) {
        latitude = "0";
      }
      if (Number(longitude) > 180 || Number(longitude) < -180) {
        longitude = "0";
      }
      console.log(item, longitude, latitude, "latitude");
      uni.openLocation({
        longitude: Number(longitude),
        latitude: Number(latitude),
        name: item.stationName,
        success: function () {
          console.log("success");
        },
        fail: function (e) {
          console.log(e, "fail");
        },
      });
    },

    rad(d) {
      return (d * Math.PI) / 180.0;
    },

    getDistances(lat2, lng2) {
      let radLat1 = this.rad(this.latitude);
      let radLat2 = this.rad(Number(lat2));
      let a = radLat1 - radLat2;
      let b = this.rad(this.longitude) - this.rad(Number(lng2));
      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137;
      // 输出为公里
      s = Math.round(s * 10000) / 10000;

      let distance = s;
      let distance_str = "";

      if (parseInt(distance) >= 1) {
        // distance_str = distance.toFixed(1) + "km";
        distance_str = distance.toFixed(2) + "km";
      } else {
        // distance_str = distance * 1000 + "m";
        distance_str = (distance * 1000).toFixed(2) + "m";
      }

      return distance_str;
    },
  },
};
</script>

<style lang="scss" scoped>
.station {
  overflow: auto;
  width: 100vw;
  min-height: 100vh;
  background-color: #f6f6f6;
  .business_model {
    background: linear-gradient(to bottom, #f6b595, #f4e7e1);
    padding: 20rpx 0 60rpx 32rpx;
    .business_name {
      color: #352b22;
      font-weight: bold;
    }
    .tip {
      color: #7c7c7c;
      font-size: 18rpx;
      padding-top: 18rpx;
    }
  }

  .swiper-box {
    background-color: #fff;
    height: 260rpx;
    .swiper-item {
      height: 220rpx;
      padding: 0 31rpx 40rpx 24rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
  }
  .station_list {
    padding: 24rpx 30rpx 0 22rpx;
    .preference {
      font-size: 24rpx;
      font-weight: bold;
      color: #000000;
    }
    .station_item {
      margin-top: 20rpx;
      background-color: #fff;
      padding: 28rpx 18.5px 37.5rpx 24rpx;
      border-radius: 12rpx;
      button {
        border: unset;
        margin: unset;
        padding: unset;
        line-height: unset;
      }
      .item_top_model {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 28rpx;
        .item_left {
          display: flex;
          align-items: center;
          color: #000000;
          font-size: 32rpx;
          font-weight: bold;
          image {
            width: 28rpx;
            height: 30rpx;
            object-fit: cover;
            margin-right: 20rpx;
          }
        }
        .item_right {
          display: flex;
          align-items: center;
          color: #7c7c7c;
          font-size: 20rpx;
          image {
            width: 16.5rpx;
            height: 18.5rpx;
            object-fit: cover;
            margin-right: 10rpx;
          }
        }
      }
      .oil_price {
        padding-left: 45rpx;
        display: flex;
        align-items: flex-end;
        view:first-child {
          display: flex;
          align-items: center;
          text:first-child {
            font-size: 24rpx;
            // font-weight: bold;
            color: #fb722e;
          }
          text:last-child {
            font-size: 36rpx;
            font-weight: bold;
            color: #fb722e;
          }
        }
        .station_price {
          font-size: 14rpx;
          color: #7c7c7c;
          padding-left: 16rpx;
        }
      }
      .oil_address {
        padding: 20rpx 0 12rpx 45rpx;
        color: #7c7c7c;
        font-size: 20rpx;
        text-align: left;
      }
      .refuel {
        display: flex;
        justify-content: flex-end;
        text {
          padding: 10rpx 12rpx;
          border-radius: 10rpx;
          background-color: #e7f0f4;
          color: #000000;
          font-size: 20rpx;
        }
      }
    }
  }
}
</style>
